package com.company.dcm.sa_token;
import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.company.dcm.entity.User;
import com.company.dcm.service.PermissionService;
import com.company.dcm.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StpInterfaceImpl implements StpInterface {
    @Autowired
    private UserService userService;
    @Autowired
    private PermissionService permissionService;

    //ID为用户名
    /**
     * 返回一个账号所拥有的权限码集合
     */
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        // 1. 声明权限码集合
        List<String> permissionList = new ArrayList<>();

        // 2. 遍历角色列表，查询拥有的权限码
//        for (String role : getRoleList(loginId, loginType)) {
//            SaSession roleSession = SaSessionCustomUtil.getSessionById("role-" + role);
//            List<String> list = roleSession.get("Permission_List", () -> {
//                return permissionService.getPermissionListByRoleId(
//                        roleService.getBaseMapper().selectOne(new LambdaQueryWrapper<Role>().eq(Role::getRole,role))
//                                .getId());// 从数据库查询这个角色所拥有的权限列表
//            });
//            permissionList.addAll(list);
//        }

//        SaSession session = StpUtil.getSessionByLoginId(loginId);
//        permissionList = session.get("Permission_List",() -> {
//            User user = userService.getExistByUserName((String) loginId);
//            return permissionService.getWorkShopIdsByUserId(user.getUserId()).stream()
//                    .map(String::valueOf)
//                    .collect(Collectors.toList());
//        });

            User user = userService.getExistByUserName((String) loginId);

            permissionList=permissionService.getWorkShopIdsByUserId(user.getUserId()).stream()
                    .map(String::valueOf)
                    .collect(Collectors.toList());


        // 3. 返回权限码集合
        return permissionList;
    }

    /**
     * 返回一个账号所拥有的角色标识集合 (权限与角色可分开校验)
     */
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
//        SaSession session = StpUtil.getSessionByLoginId(loginId);
//        return session.get("Role_List", () -> {
//            User user = userService.getExistByUserName((String) loginId);
//            List<String> result=new ArrayList<>();
//            result.add(user.getRoleId().toString());
//            return result;
//        });

            User user = userService.getExistByUserName((String) loginId);
            List<String> result=new ArrayList<>();
            result.add(user.getRoleId().toString());
            return result;
    }
}


